import { message, Button, Divider, Select,notification } from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect } from 'umi'
import { getInsuranceList, saveOrUpdateInsurance, deleteSecurity } from '../service'
import CreateForm from './components/CreateForm'
import moment from 'moment'
import { insuranceStatusList } from '@/utils/constant'
import { getCompanyListAuth } from '@/pages/Security/service'

const { Option } = Select

const TableList = (props) => {
  const { currentUser } = props
  const { authorities } = currentUser
  const actionRef = useRef()
  const [securityType] = useState(0)
  const [done, setDone] = useState(false)
  const [visible, setVisible] = useState(false)
  const [current, setCurrent] = useState(undefined)
  const [loading, setLoading] = useState(false)
  const [contractData, setContractData] = useState(null)

  useEffect(() => {
    getCompanyListAuth().then(res => {
      if(res.flag){
        res && setContractData(res.data)
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
    })
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'promotionId',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '被保险单位',
      dataIndex: 'companyName',
      hideInSearch: true,
    },
    {
      title: '被保险单位',
      dataIndex: 'companyId',
      hideInTable: true,
      renderFormItem: (item, props) => {
        return <Select placeholder="请选择参保单位" showSearch allowClear
                       filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
          {contractData.length > 0 ? contractData.map((item, index) => {
            return (
              <Option value={item.id} key={index} lable={item}>
                {item.name}
              </Option>
            )
          }) : ''}
        </Select>
      },
    },
    {
      title: '承保单位',
      dataIndex: 'insuranceUnit',
    },
    {
      title: '保险开始时间',
      dataIndex: 'startDate',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD')
    },
    {
      title: '保险结束时间',
      dataIndex: 'endDate',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD')
    },
    {
      title: '单价',
      dataIndex: 'money',
      hideInSearch: true,
    },
    {
      title: '在保人数',
      dataIndex: 'realNumber',
      hideInSearch: true,
    },
    {
      title: '投保人数',
      dataIndex: 'maxNumber',
      hideInSearch: true,
    },
    {
      title: '生效状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        2: { text: insuranceStatusList[0].label, status: 'Default' },
        1: { text: insuranceStatusList[1].label, status: 'Success' },
      },
    },
    {
      title: '操作人',
      dataIndex: 'operateName',
      hideInSearch: true,
    },
    {
      title: '操作日期',
      dataIndex: 'operateTime',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD')
    },
    {
      title: '附件',
      dataIndex: 'fileUrl',
      hideInSearch: true,
      render: (text) => {
        let urlArray = text !== '-' ? text.split(',') : []
        return urlArray.map((item, index) => {
          return <div key={index}><a onClick={() => window.open(item)}>{item.split('----')[1]}</a></div>
        })
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      render: (item, record) => (
        <>
          {<a onClick={() => updatePlan(record)}>修改方案</a>}
          {/*{<Divider type="vertical"/>}
          {<a onClick={() => setPlanPerson(record)}>编辑人员</a>}*/}
          <Divider type="vertical"/>
          {
            record.status === 1 ?
              <a onClick={() => termination(record)}>终止</a> :
              <a onClick={() => release(record)}>发布</a>
          }
        </>
      ),
    },
  ]

  const handleCancel = () => {
    setCurrent(null)
    setVisible(false)
  }

  const addPlan = () => {
    setVisible(true)
  }

  const updatePlan = (record) => {
    setVisible(true)
    setCurrent(record)
  }

  const release = (record) => {
    let data = { id: record.id, status: 1 }
    setLoading(true)
    saveOrUpdateInsurance(data).then(res => {
      if (res.flag) {
        message.success('方案发布成功！')
        actionRef.current.reload()
      } else {
        message.error(`操作失败！ ${res.error}`)
      }
      setLoading(false)
    })
  }

  const termination = (record) => {
    setLoading(true)
    deleteSecurity(record.id).then(res => {
      if (res.flag) {
        message.success('方案终止成功！')
        actionRef.current.reload()
      } else {
        message.error(`操作失败！ ${res.error}`)
      }
      setLoading(false)
    })
  }

  const handleSubmit = (values) => {
    let { date, ...restValues } = values
    setLoading(true)
    setDone(false)
    setCurrent(null)
    setVisible(false)
    let startDate = date[0]
    let endDate = date[1]
    saveOrUpdateInsurance({ startDate, endDate, ...restValues }).then((req) => {
      if (req.flag) {
        message.success('方案信息保存成功！')
        actionRef.current.reload()
      } else {
        message.error(`操作保存失败！${req.error}`)
      }
      setLoading(false)
    })
  }

  return (
    <PageHeaderWrapper>

      {
        contractData && <ProTable
          actionRef={actionRef}
          loading={loading}
          rowKey="id"
          request={(params) => getInsuranceList(params)}
          columns={columns}
          toolBarRender={(action, { selectedRows }) => [
            <Button type="primary" onClick={() => addPlan()}>新建</Button>,
          ]}
        />
      }
      <CreateForm
        type={securityType}
        done={done}
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />

    </PageHeaderWrapper>
  )
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(TableList)
